using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Configuration;

namespace CallFlowDesigner
{
    

    static class Program
    {

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            
            if (OkToRun())Application.Run(new CallFlowDesigner());
        }


		 //check that cert file is set up OK in config.
		  static bool OkToRun()
		  {
			  string certFileName = "";
			  string path = Assembly.GetExecutingAssembly().Location;
				  
			  try
			  {
				  certFileName = ConfigurationManager.AppSettings["certFile"];
				  if (!System.IO.File.Exists(certFileName))
				  {
						MessageBox.Show("Cannot load your Certificate from BT - please check your .config to make sure it's set up OK. In particular look for certFile and certPassword", "CallFlow Designer", MessageBoxButtons.OK, MessageBoxIcon.Error);	  
						LoadConfig(path);
					   return false;
				  }

				  X509Certificate x509 = new X509Certificate(certFileName, ConfigurationManager.AppSettings["certPassword"]);
				  return true;
			  }
			  catch (CryptographicException)
			  {
					  MessageBox.Show("Cannot load your Certificate from BT - please check certPassword in your .config is correct ", "CallFlow Designer", MessageBoxButtons.OK, MessageBoxIcon.Error);
					  path = LoadConfig(path);
					  return false;
				
			  }
			  catch (FileNotFoundException)
			  {
				  MessageBox.Show("Cannot load your .config file. Should be at " + Assembly.GetExecutingAssembly().Location + ".config", "CallFlow Designer", MessageBoxButtons.OK, MessageBoxIcon.Error);
				  return false;
			  }
			  catch (Exception)
			  {
				  MessageBox.Show("Unknown Error checking cert", "CallFlow Designer", MessageBoxButtons.OK, MessageBoxIcon.Error);
				  return false;
			  }
		  }

		  private static string LoadConfig(string path)
		  {
			  if (!Debugger.IsAttached)
			  {
				  ProcessStartInfo psi = new ProcessStartInfo();
				  psi.FileName = "notepad.exe";
				  psi.Arguments = path + ".config";

				  if (System.IO.File.Exists(psi.Arguments))
				  {
					  Process.Start(psi);
				  }
			  }
			  else //assume running in IDE.
			  {
				  path = path.Replace("\\bin\\Debug", "");
				  path = path.Substring(0, path.LastIndexOf("\\") + 1);
				  ProcessStartInfo psi = new ProcessStartInfo(path + "app.config");
				  Process.Start(psi);
			  }

			  return path;
		  }
    }
}